package top.lyc829.zzl_android.ui.profile.follow.user;

import androidx.lifecycle.ViewModelProvider;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.chad.library.adapter.base.listener.OnLoadMoreListener;
import com.google.gson.Gson;

import java.io.IOException;

import okhttp3.Response;
import top.lyc829.zzl_android.R;
import top.lyc829.zzl_android.databinding.FollowUserFragmentBinding;
import top.lyc829.zzl_android.logic.bean.ResultBean;
import top.lyc829.zzl_android.logic.bean.UserInfoBean;
import top.lyc829.zzl_android.logic.network.Network;
import top.lyc829.zzl_android.logic.util.FellowType;
import top.lyc829.zzl_android.logic.util.HttpUtil;
import top.lyc829.zzl_android.logic.util.PageInfo;
import top.lyc829.zzl_android.logic.util.Utils;
import top.lyc829.zzl_android.ui.profile.follow.user_detail.OtherUserDetailActivity;
import top.lyc829.zzl_android.ui.thing.dynamic_detail.DynamicDetailViewModel;

public class FollowUserFragment extends Fragment {

    private FollowUserViewModel mViewModel;
    FollowUserAdapter adapter ;
    FollowUserFragmentBinding binding ;
    private DynamicDetailViewModel dViewModel;

    private int otherUserId = -1;
    public static FollowUserFragment newInstance() {
        return new FollowUserFragment();
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        binding = FollowUserFragmentBinding.inflate(getLayoutInflater());
        return binding.getRoot();
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mViewModel = new ViewModelProvider(this).get(FollowUserViewModel.class);

        GridLayoutManager layoutManager = new GridLayoutManager(getActivity(), 1);
        binding.followUserRecyclerview.setLayoutManager(layoutManager);
        adapter = new FollowUserAdapter();
        adapter.setAnimationEnable(true);   // recyclerview加载动画
        binding.followUserRecyclerview.setAdapter(adapter);
      //  adapter.setList(new UserInfoBean().getExamples());

//点击事件
       adapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                Intent intent = new Intent(getActivity(), OtherUserDetailActivity.class);//用户信息详情界面
                intent.putExtra("id", ((UserInfoBean) adapter.getData().get(position)).getId());
                startActivity(intent);
            }
        });
        adapter.addChildClickViewIds(R.id.followed_user_attentioned);
        adapter.setOnItemChildClickListener((adapter1,view,position)->{
            if(view.getId()==R.id.followed_user_attentioned)
            {
                    Network.unAttention(Utils.getUserId(), FellowType.USER,adapter.getItem(position).getId(), new HttpUtil.MyCallback() {
                        @Override
                        public void success(Response res) throws IOException {
                            String resultStr = res.body().string();
                            ResultBean resultBean = new Gson().fromJson(resultStr, ResultBean.class);
                            if (resultBean.getCode().equals(200)) {
                                //重新返回列表
                                request();
                            } else {
                                failed(new IOException());
                            }
                        }

                        @Override
                        public void failed(IOException e) {
                            Utils.showToastSync("取消关注失败");
                        }
                    });
            }
        });

        /*mViewModel.getFollowUserList(1);
        mViewModel.getFollowUserLiveData().observe(getViewLifecycleOwner(), new Observer<List<UserInfoBean>>() {
            @Override
            public void onChanged(List<UserInfoBean> userInfoBeans) {
                adapter.setList(userInfoBeans);
            }
        });*/

        request();
        binding.swipeLayout.setRefreshing(true);
        refresh();
        initRefreshLayout();
//        initLoadMore();
        observe();
    }

//    private void initLoadMore() {
//        adapter.getLoadMoreModule().setOnLoadMoreListener(new OnLoadMoreListener() {
//            @Override
//            public void onLoadMore() {
//                request();
//            }
//        });
//        adapter.getLoadMoreModule().setAutoLoadMore(true);
//        //当自动加载开启，同时数据不满一屏时，是否继续执行自动加载更多(默认为true)
//        adapter.getLoadMoreModule().setEnableLoadMoreIfNotFullPage(false);
//    }

    private void initRefreshLayout() {
        binding.swipeLayout.setColorSchemeColors(Color.rgb(47, 223, 189));
        binding.swipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                refresh();
            }
        });
    }

    /**
     * 刷新
     */
    private void refresh() {
        // 这里的作用是防止下拉刷新的时候还可以上拉加载
        adapter.getLoadMoreModule().setEnableLoadMore(false);
        // 下拉刷新，需要重置页数
        request();
    }
    private void request() {
        if(otherUserId==-1) {
            mViewModel.getFollowUserList(Utils.getUserId());
        }
        else
        {
            mViewModel.getFollowUserList(otherUserId);
            //这里同理
        }
    }


    //观察者
    private void observe()
    {
        mViewModel.getFollowUserLiveData().observe(getViewLifecycleOwner(), userInfoBeans->
        {
            if (userInfoBeans == null || userInfoBeans.size() == 0) {
                binding.swipeLayout.setRefreshing(false);
                adapter.setList(userInfoBeans);
                adapter.getLoadMoreModule().loadMoreComplete();
                return;
            }

            if (otherUserId != Utils.getUserId()) {
                userInfoBeans.forEach(userInfoBean -> {
                    userInfoBean.setIsLike("-1");
                });
            }
            else if (otherUserId == Utils.getUserId()) {
                userInfoBeans.forEach(userInfoBean -> {
                    userInfoBean.setIsLike("-2");
                });
            }

            binding.swipeLayout.setRefreshing(false);
            adapter.setList(userInfoBeans);
            adapter.getLoadMoreModule().loadMoreComplete();
        });

    }
    @Override
    public void onResume() {
        super.onResume();
        refresh();

    }
    public void setOtherUserId(int otherUserId) {
        this.otherUserId = otherUserId;
    }
}